package com.eddy.project.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.StringJoiner;

@Component
@Aspect
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    /**
     * ========== xxxService.xxx() start ==========
     * 接口请求时间
     * 接口请求参数
     * 接口请求耗时
     * ========== xxxService.xxx() end ==========
     *
     * @param joinPoint
     */
    @Around("execution(* com.eddy.project.service..*.*(..))")
    public Object sysLog(ProceedingJoinPoint joinPoint) throws Throwable {
//        StringJoiner log = new StringJoiner("|", "{", "}");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss");
        String format = formatter.format(LocalDateTime.now());


//        joinPoint.getSignature().getName(); // 获取目标方法名
//        joinPoint.getSignature().getDeclaringType().getSimpleName(); // 获取目标方法所属类的简单类名
//        joinPoint.getSignature().getDeclaringTypeName(); // 获取目标方法所属类的类名
//        joinPoint.getSignature().getModifiers(); // 获取目标方法声明类型(public、private、protected)
//        Object[] args = joinPoint.getArgs(); // 获取传入目标方法的参数，返回一个数组
//        joinPoint.getTarget(); // 获取被代理的对象
//        joinPoint.getThis(); // 获取代理对象自己

        // 获取目标方法所属类的简单类名
        String simpleName = joinPoint.getSignature().getDeclaringType().getSimpleName();
        //当前执行的业务方法名称
        String methodName = joinPoint.getSignature().getName();


        //方法的参数
        StringJoiner argsStr = new StringJoiner(",", "{", "}");
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            argsStr.add(arg == null ? "-" : arg.toString());
        }

        StringJoiner stringJoiner = new StringJoiner("\r\n");
        stringJoiner.add("");
        stringJoiner.add("========== " + simpleName + "." + methodName + "() start ==========");
        stringJoiner.add("接口请求时间:" + format);
        stringJoiner.add("接口请求参数:" + argsStr);
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        stringJoiner.add("接口请求耗时:" + (endTime - startTime));
        stringJoiner.add("========== " + simpleName + "." + methodName + "() end==========");
        logger.info(stringJoiner.toString());

        return result;
    }
}
